package com.reef.controller;


import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.reef.dao.StudentRepository;
import com.reef.dto.ReaderDto;
import com.reef.entity.Reader;
import com.reef.entity.Result;
import com.reef.service.StudentService;
@RestController
public class StudentController {
	@Autowired
	private StudentRepository stuRepository;
	@Autowired
	private StudentService stuService;
	/**
	 * 多条件动态查询
	 */
	/**
	 * 多条件动态查询
	 */
	@RequestMapping("/findcondition")
	public Object findByCondition(ReaderDto sDto,int page,int limit) {
		//getTotalElements()指实体中有多少元素
		//分页查询 springBoot2.0以下版本用new 实例化，2.0以上版本使用的是PageRequest
		Pageable pageable = PageRequest.of(page-1, limit);
		Page<Reader> pagelist  = stuService.findByCondition(sDto, pageable);
		Map<String, Object> map =new HashMap<String, Object>();
		map.put("code", 0);
		map.put("msg", "");
		map.put("count", pagelist.getTotalElements());
		map.put("data", pagelist.getContent());
		return map;
	}
	/**
	 * 查询专业
	 */
	@RequestMapping("/selProfession")
	public Object selProfession() {
		return stuRepository.selProfession();
	}

	
	/**
	 * 封装姓名，借书量，还书量
	 */
	@RequestMapping("/queryBar")
	public Object queryByBar(String reader) {
		List<Reader> list = stuService.getAll(reader);
		
		//声明存储姓名的集合
		List<String> nameList = new ArrayList<String>();
		//声明借书集合
		List<Integer> borrowList = new ArrayList<Integer>();
		//声明还书集合
		List<Integer> givenList = new ArrayList<Integer>();
		//遍历list集合获取对应值存储相应集合
		for(Reader stu:list) {
			nameList.add(stu.getName());
			borrowList.add(stu.getBorrowbook());
			givenList.add(stu.getGivenbook());
		}
		Map<String,Object> map = new HashMap<String, Object>();
		map.put("name",nameList );
		map.put("borrow", borrowList);
		map.put("given", givenList);
		return map;
	}
	/**
	 * 添加学生信息
	 */
	
	@RequestMapping("/insertStu")
	public Object insertStu(Reader reader) {
		Reader i=stuService.insertStu(reader);
		if(i==null) {
			return new Result("添加失败","",false);
		}else {
			return new Result("添加成功","",true);
		}
	}
	/**
	 * 修改学生信息
	 */
	@RequestMapping("/updateStu")
	public Object updateStu(Reader reader) {
		Reader i=stuService.updateStu(reader);
		if(i==null) {
			return new Result("修改失败","",false);
		}else {
			return new Result("修改成功","",true);
		}
	}
}
